//
//  TakePhotoViewController.m
//  CarLifes
//
//  Created by yu on 2017/6/20.
//  Copyright © 2017年 jpas. All rights reserved.
//  

#import "TakePhotoViewController.h"
#import "CustomButton.h"
#import "XLPhotoBrowser.h"
#import "Utility.h"
#import "TraceModel.h"
#import "EquipmentModel.h"
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import "LocationManager.h"
#import "DeviceVersion.h"

#define DefaultLocationTimeout 10
#define DefaultReGeocodeTimeout 5

@interface TakePhotoViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,XLPhotoBrowserDelegate,XLPhotoBrowserDatasource>
{
    UIImageView *_firstImgView;
    UIImageView *_secondImgView;
    UIImageView *_thirdImgView;
//    UIImageView *_fourthImgView;
    
    UIButton *_firstButton;
    UIButton *_secondButton;
    UIButton *_thirdButton;
//    UIButton *_fourthButton;
    
    UIButton *_firstBtn;
    UIButton *_secondBtn;
    UIButton *_thirdBtn;
//    UIButton *_fourthBtn;
    
    UIView *_firstSectionContainer;
    UIView *_secondSectionContainer;
    UIView *_thirdSectionContainer;
    UIView *_fourthSectionContainer;
    
    BOOL _isRetakePhoto;
    
    UITextField *_installerTextField;
    UITextField *_phoneNumTextField;
    
    CLLocation *_location;
    
    UILabel *_locationLabel;
    UILabel *_timeLabel;
    UILabel *_statusLabel;
    
    BOOL _isLBSLocation;
    BOOL _isUnActive;
    BOOL _presentNextPage;
    double _latitude;
    double _longitude;
    NSString *_postType;
    NSString *_positionTimeString;
    NSString *_status;
    
    NSDate *_positionTime;
    NSDate *_phonePositionTime;
    
    NSString *_installerPosition;
    NSString *_eqPosition;
}

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (nonatomic, strong) UIView *wrapperView;

@property (nonatomic, strong) UIButton *submitButton;

@property (nonatomic, strong) UIImagePickerController *imagePicker;

@property (nonatomic, strong) UIButton *tempButton;

@property (nonatomic, strong) UIButton *tempRetakeBtn;

@property (nonatomic, strong) UIImageView *tempImageView;

//用于临时存储照片
@property (nonatomic, strong) NSMutableArray *imagesArray;

@property (nonatomic, strong) NSMutableArray *types;

@property (nonatomic, strong) NSTimer *timer;

// Color
@property (nonatomic, strong) UIColor *textColor;
@property (nonatomic, strong) UIColor *textFieldBgColor;
@property (nonatomic, strong) UIColor *sectionContainerColor;

@end

@implementation TakePhotoViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.navigationItem.title = self.uploadType == UploadImgTypeNormal?@"安装拍照":@"补拍";
    
    if (self.uploadType == UploadImgTypeNormal) {
        [self getLocation];
    }
    
    [self updateEqStatus];
    [self loadRealTraceData];
    [self initTimer];
    
    self.wrapperView = [[UIView alloc] init];
    if (@available(iOS 13.0, *)) {
        self.wrapperView.backgroundColor = UIColor.systemBackgroundColor;
    } else {
        self.wrapperView.backgroundColor = UIColor.whiteColor;
    }
    [self.scrollView addSubview:self.wrapperView];
    [self.scrollView setupAutoContentSizeWithBottomView:self.wrapperView bottomMargin:0];
    
    // 第一组
    [self setupFirstSectionCell];
    // 第二组
    [self setupSecondSectionCell];
    // 第三组
    [self setupThirdSectionCell];
    // 第四组
    [self setupFourthSectionCell];
    
    self.wrapperView.sd_layout
    .leftEqualToView(self.scrollView)
    .rightEqualToView(self.scrollView)
    .topEqualToView(self.scrollView);
    [self.wrapperView setupAutoHeightWithBottomView:self.submitButton bottomMargin:35];
    
    [self setLeftImageNamed:@"back_white" action:@selector(returnAction)];
}

- (UIColor *)textFieldBgColor
{
    if (_textFieldBgColor == nil) {
        if (@available(iOS 13.0, *)) {
            _textFieldBgColor = UIColor.tertiarySystemBackgroundColor;
        } else {
            _textFieldBgColor = UIColor.whiteColor;
        }
    }
    return _textFieldBgColor;
}

- (UIColor *)textColor
{
    if (_textColor == nil) {
        if (@available(iOS 13.0, *)) {
            _textColor = [UIColor.labelColor colorWithAlphaComponent:0.85];
        } else {
            _textColor = kTextBlackColor;
        }
    }
    return _textColor;
}

- (UIColor *)sectionContainerColor
{
    if (_sectionContainerColor == nil) {
        if (@available(iOS 13.0, *)) {
            _sectionContainerColor =  [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
                if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                    return kBackgroundColor;
                } else {
                    return UIColor.secondarySystemGroupedBackgroundColor;
                }
            }];
        } else {
            _sectionContainerColor = kBackgroundColor;
        }
    }
    return _sectionContainerColor;
}

- (void)returnAction
{
    _presentNextPage = NO;
    if ([self.takePhotoType isEqualToString:@"1"]) {
        UIViewController *vc = self.navigationController.viewControllers[2];
        [self.navigationController popToViewController:vc animated:YES];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)initTimer
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:10.0
                                                  target:self
                                                selector:@selector(timerAction)
                                                userInfo:nil
                                                 repeats:YES];
    //    self.timer.fireDate = [NSDate distantPast];// 开启定时
     [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)timerAction
{
    [self updateEqStatus];//获取设备状态
    [self loadRealTraceData];//获取实时轨迹
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (_presentNextPage == NO)
    {
        [self.timer invalidate];
        self.timer = nil;
        // 不停止定位，退出界面还会持续定位
        [LocationManager stopUpdatingLocation];
    }
}

- (void)updateEqStatus
{
    [self.requestTool loadEquipmentStatusStr:self.eqnoModel.eqNo success:^(NSArray *eqList) {
        EquipmentModel *eq = eqList.lastObject;
        _status = eq.status;
        _isUnActive = [_status isEqualToString:@"3"];
        _statusLabel.text = NSStringFormat(@"设备状态：%@",self.status);
    } failure:^(NSError *error) {
        PPLog(@"<拍照>获得设备状态错误：%@",error);
    }];
}

- (void)loadRealTraceData
{
    [self.requestTool loadRealTrackByEqno:self.eqnoModel.eqNo show:NO success:^(TraceModel *traceModel) {
        _latitude = [traceModel.gdLat doubleValue];
        _longitude = [traceModel.gdLng doubleValue];
        _postType = traceModel.postType;
        _positionTime = [Utility stringToDateFromFormat:@"yyyy-MM-dd HH:mm:ss" timeStr:traceModel.positionTime];
        _positionTimeString = traceModel.positionTime;
        _isLBSLocation = [_postType isEqualToString:@"LBS"];

        // 设备逆地理
        [self searchReGeocodeWithCoordinate1:CLLocationCoordinate2DMake(_latitude, _longitude)];
//        _statusLabel.text = NSStringFormat(@"设备状态：%@",self.status);
        _timeLabel.text = NSStringFormat(@"定位时间：%@",_positionTimeString ? : @"获取失败");
    } failure:^(NSError *error) {
        PPLog(@"<拍照>real track error = %@",error.description);
    }];
}

- (NSString *)status
{
    if (_status.length) {
        if ([_status isEqualToString:@"3"]) {
            return @"未启用";
        } else if ([_status isEqualToString:@"2"]) {
            return @"离线";
        } else {
            return @"在线";
        }
    } else {
        return @"正在获取...";
    }
}

- (void)getLocation
{
    [LocationManager getLocationInfo:^(double lat, double lng, AMapLocationReGeocode *reGeocode) {
        PPLog(@"***lat = %lf,***lng = %lf",lat,lng);
        _location = [[CLLocation alloc] initWithLatitude:lat longitude:lng];
        _phonePositionTime = [NSDate date];
        // 返回数据不全,_installerPosition应使用AMapSearchKit的逆地理功能获取
        // _installerPosition = reGeocode.formattedAddress;
        [self searchReGeocodeWithCoordinate2:_location.coordinate];
    }];
}

- (void)setupFirstSectionCell {
    UIView *firstSectionContainer = [UIView new];
    firstSectionContainer.backgroundColor = self.sectionContainerColor;
    _firstSectionContainer = firstSectionContainer;
    
    {
        UILabel *agencyLabel = [self titleLabelWithText:NSStringFormat(@"经销商名称：%@",self.eqnoModel.eqDeptName) bgColor:[UIColor clearColor] textColor:self.textColor font:17];
        
        UILabel *installerLabel = [self titleLabelWithText:@"安装人姓名：" bgColor:[UIColor clearColor] textColor:self.textColor font:17];
        [installerLabel sizeToFit];
        
        UITextField *installerTextField = [[UITextField alloc] init];
        _installerTextField = installerTextField;
        installerTextField.backgroundColor = self.textFieldBgColor;
        installerTextField.textColor = self.textColor;
        
        UILabel *phoneNumLabel = [self titleLabelWithText:@"安装人电话：" bgColor:[UIColor clearColor] textColor:self.textColor font:17];
        
        UITextField *phoneNumTextField = [[UITextField alloc] init];
        _phoneNumTextField = phoneNumTextField;
        phoneNumTextField.keyboardType = UIKeyboardTypeASCIICapableNumberPad;
        phoneNumTextField.backgroundColor = self.textFieldBgColor;
        phoneNumTextField.textColor = self.textColor;
        
        // 加载安装人员信息
        if (self.uploadType == UploadImgTypeSupplement) {
            NSDictionary *dict = self.installInfo;
            installerTextField.text = [dict[@"installer"] isEqual:[NSNull class]] ? dict[@"installer"] : @"";
            installerTextField.enabled = NO;
            installerTextField.backgroundColor = kBackgroundColor;
            
            phoneNumTextField.text = [dict[@"installerPhone"] isEqual:[NSNull class]] ? dict[@"installerPhone"] : @"";
            phoneNumTextField.enabled = NO;
            phoneNumTextField.backgroundColor = kBackgroundColor;
        }
        
        UILabel *ownerLabel = [self titleLabelWithText:NSStringFormat(@"车 主 姓 名：%@",self.eqnoModel.ownerName) bgColor:[UIColor clearColor] textColor:self.textColor font:17];

        [firstSectionContainer sd_addSubviews:@[agencyLabel,installerLabel,installerTextField,phoneNumLabel,phoneNumTextField,ownerLabel]];

        agencyLabel.sd_layout
        .topSpaceToView(firstSectionContainer, 10)
        .leftSpaceToView(firstSectionContainer, 15)
        .rightSpaceToView(firstSectionContainer, 15)
        .heightIs(25);
        
        installerLabel.sd_layout
        .topSpaceToView(agencyLabel, 5)
        .leftEqualToView(agencyLabel)
        .heightRatioToView(agencyLabel, 1)
        .widthIs(105);
        
        installerTextField.sd_layout
        .centerYEqualToView(installerLabel)
        .leftSpaceToView(installerLabel, 0)
        .heightIs(28)
        .rightSpaceToView(firstSectionContainer, 15);
        
        phoneNumLabel.sd_layout
        .topSpaceToView(installerLabel, 5)
        .leftEqualToView(installerLabel)
        .heightRatioToView(installerLabel, 1)
        .widthRatioToView(installerLabel, 1);
        
        phoneNumTextField.sd_layout
        .centerYEqualToView(phoneNumLabel)
        .leftSpaceToView(phoneNumLabel, 0)
        .heightIs(28)
        .rightSpaceToView(firstSectionContainer, 15);
        
        ownerLabel.sd_layout
        .leftEqualToView(phoneNumLabel)
        .topSpaceToView(phoneNumLabel, 5)
        .rightSpaceToView(firstSectionContainer, 15)
        .heightRatioToView(phoneNumLabel, 1);
        
        [firstSectionContainer setupAutoHeightWithBottomView:ownerLabel bottomMargin:8];
    }
    
    [self.wrapperView addSubview:firstSectionContainer];
    
    firstSectionContainer.sd_layout
    .leftEqualToView(self.wrapperView)
    .topEqualToView(self.wrapperView)
    .rightEqualToView(self.wrapperView);
}

- (void)setupSecondSectionCell {

    UIView *secondSectionContainer = [UIView new];
    secondSectionContainer.backgroundColor = self.sectionContainerColor;
    _secondSectionContainer = secondSectionContainer;
    {
        UILabel *equipLabel = [self titleLabelWithText:NSStringFormat(@"设备号：%@",self.eqnoModel.eqNo) bgColor:[UIColor clearColor] textColor:self.textColor font:17];
        UILabel *SIMLabel = [self titleLabelWithText:NSStringFormat(@"SIM号 ：%@",self.eqnoModel.sim) bgColor:[UIColor clearColor] textColor:self.textColor font:17];
        
        [secondSectionContainer sd_addSubviews:@[equipLabel,SIMLabel]];
        
        equipLabel.sd_layout
        .leftSpaceToView(secondSectionContainer, 15)
        .rightSpaceToView(secondSectionContainer, 15)
        .topSpaceToView(secondSectionContainer, 10)
        .heightIs(20);
        
        SIMLabel.sd_layout
        .leftEqualToView(equipLabel)
        .topSpaceToView(equipLabel, 5)
        .rightSpaceToView(secondSectionContainer, 15)
        .heightRatioToView(equipLabel, 1);
        
        [secondSectionContainer setupAutoHeightWithBottomView:SIMLabel bottomMargin:10];
    }
    
    [self.wrapperView addSubview:secondSectionContainer];
    
    secondSectionContainer.sd_layout
    .leftEqualToView(self.wrapperView)
    .topSpaceToView(_firstSectionContainer, 8)
    .rightEqualToView(self.wrapperView);
}

- (void)setupThirdSectionCell {
    UIView *thirdSectionContainer = [UIView new];
    thirdSectionContainer.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.5];
//    thirdSectionContainer.backgroundColor = self.sectionContainerColor;
    _thirdSectionContainer = thirdSectionContainer;
    
    NSMutableArray *temp = [NSMutableArray new];

//    NSMutableArray *titles = [NSMutableArray arrayWithObjects:@"设备号、SIM卡号和车架号",@"车辆前45°",@"安装完成照片",@"车内装饰照片", nil];
    NSMutableArray *titles = [NSMutableArray arrayWithObjects:@"图片一",@"图片二",@"图片三", nil];
    NSMutableArray *allTypes = [NSMutableArray arrayWithObjects:@"1",@"2",@"3", nil];
    
    NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
    
    for (NSNumber *number in self.indexImg) {
        [indexSet addIndex:number.integerValue - 1];
    }
    
    [titles removeObjectsAtIndexes:indexSet];
    [allTypes removeObjectsAtIndexes:indexSet];
    
    self.types = allTypes;
    
    for (int i = 0; i < titles.count; i++) {
        
        UIButton *btn = [CustomButton buttonWithTitle:titles[i] bgColor:self.sectionContainerColor image:@"photo" font:17];
        btn.tag = i + 10;
        [thirdSectionContainer addSubview:btn];
    
        [btn addTarget:self action:@selector(takePhotoClick:) forControlEvents:UIControlEventTouchUpInside];
        
        btn.titleLabel.sd_layout
        .leftSpaceToView(btn, 25);
        
        btn.imageView.sd_layout
        .rightSpaceToView(btn, 25)
        .widthRatioToView(btn.imageView, 1)
        .heightRatioToView(btn.imageView, 1);
        
  //============================================
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.tag = i + 20;
        imageView.hidden = YES;
        self.tempImageView = imageView;
        imageView.userInteractionEnabled = YES;
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.backgroundColor = [UIColor whiteColor];
        [btn addSubview:imageView];
        
        UITapGestureRecognizer *tapImage = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImageView:)];
        [imageView addGestureRecognizer:tapImage];
        
        UIButton *retakeBtn = [[UIButton alloc] init];
        retakeBtn.tag = i + 30;
        self.tempRetakeBtn = retakeBtn;
        retakeBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
        [retakeBtn setTitle:[NSString stringWithFormat:@"「%@」重拍",titles[i]] forState:UIControlStateNormal];
        retakeBtn.titleLabel.font = SYSTEM_FONT(15.5);
        [retakeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [retakeBtn addTarget:self action:@selector(retakePhotoClick:) forControlEvents:UIControlEventTouchUpInside];
        [imageView addSubview:retakeBtn];
        
        imageView.sd_layout
        .leftSpaceToView(btn, 0)
        .rightSpaceToView(btn, 0)
        .topSpaceToView(btn, 2)
        .bottomSpaceToView(btn, 2);
        
        retakeBtn.sd_layout
        .leftEqualToView(imageView)
        .bottomEqualToView(imageView)
        .rightEqualToView(imageView)
        .heightIs(45);
        
        btn.sd_layout.autoHeightRatio(0.2);
        [temp addObject:btn];
    }
    
    [thirdSectionContainer setupAutoWidthFlowItems:[temp copy] withPerRowItemsCount:1 verticalMargin:0.5 horizontalMargin:0 verticalEdgeInset:0 horizontalEdgeInset:0];
    
    [self.wrapperView addSubview:thirdSectionContainer];
    
    _thirdSectionContainer.sd_layout
    .leftSpaceToView(self.wrapperView, 0)
    .rightSpaceToView(self.wrapperView, 0)
    .topSpaceToView(_secondSectionContainer, 8);
    
    _firstButton  = (UIButton *)[self.view viewWithTag:10];
    _secondButton = (UIButton *)[self.view viewWithTag:11];
    _thirdButton  = (UIButton *)[self.view viewWithTag:12];
//    _fourthButton  = (UIButton *)[self.view viewWithTag:13];
    
    _firstBtn = (UIButton *)[self.view viewWithTag:30];
    _secondBtn = (UIButton *)[self.view viewWithTag:31];
    _thirdBtn = (UIButton *)[self.view viewWithTag:32];
//    _fourthBtn = (UIButton *)[self.view viewWithTag:33];
    
    _firstImgView  = (UIImageView *)[self.view viewWithTag:20];
    _secondImgView = (UIImageView *)[self.view viewWithTag:21];
    _thirdImgView  = (UIImageView *)[self.view viewWithTag:22];
//    _fourthImgView  = (UIImageView *)[self.view viewWithTag:23];
}

#pragma mark - AMapReGeocodeSearchRequest

- (void)searchReGeocodeWithCoordinate1:(CLLocationCoordinate2D)coordinate
{
    [ReGeocodeManager searchReGeocodeWithCoordinate:coordinate reGeocodeBlock:^(AMapReGeocode *reGeocode) {
        AMapPOI *poi = reGeocode.pois[0];
        NSString *address = reGeocode.formattedAddress;
        NSString *name = poi.name;
        if ([address containsString:name]) name = @"";
        _eqPosition = NSStringFormat(@"%@%@ %@ %ld米",address,name,[Utility turnDirection:poi.direction],poi.distance);
        //PPLog(@"currentThread === %@",[NSThread currentThread]);
        _locationLabel.text = NSStringFormat(@"定位位置：%@(%@定位)(%lf,%lf)",_eqPosition,_postType,_latitude,_longitude);
        PPLog(@"<拍照> 设备位置：%@",_locationLabel.text);
    } reGeocodeFailBlock:^(NSString *errcode) {
        PPLog(@"<拍照> 设备位置解析错误：%@",errcode);
        [MBProgressHUD showToast:NSStringFormat(@"设备位置解析错误：%@",errcode)];
    }];
}

- (void)searchReGeocodeWithCoordinate2:(CLLocationCoordinate2D)coordinate
{
    [ReGeocodeManager searchReGeocodeWithCoordinate:coordinate reGeocodeBlock:^(AMapReGeocode *reGeocode) {
        AMapPOI *poi = reGeocode.pois[0];
        NSString *address = reGeocode.formattedAddress;
        NSString *name = poi.name;
        if ([address containsString:name]) name = @"";
        _installerPosition = NSStringFormat(@"%@%@ %@ %ld米",address,name,[Utility turnDirection:poi.direction],poi.distance);
        PPLog(@"<拍照> 手机位置：%@",_installerPosition);
    } reGeocodeFailBlock:^(NSString *errcode) {
        PPLog(@"<拍照> 手机定位解析错误：%@",errcode);
        [MBProgressHUD showToast:NSStringFormat(@"手机定位解析错误：%@",errcode)];
    }];
}

#pragma mark - FourthSection

- (void)setupFourthSectionCell {
    UIView *fourthSectionContainer = [UIView new];
    fourthSectionContainer.backgroundColor = self.sectionContainerColor;
    _fourthSectionContainer = fourthSectionContainer;
    {
        UILabel *statusLabel = [self titleLabelWithText:NSStringFormat(@"设备状态：%@",self.status) bgColor:[UIColor clearColor] textColor:self.textColor font:17];
        _statusLabel = statusLabel;
        
        UILabel *locationLabel = [self titleLabelWithText:NSStringFormat(@"定位位置：无位置信息") bgColor:[UIColor clearColor] textColor:self.textColor font:17];
        _locationLabel = locationLabel;
        
        UILabel *timeLabel = [self titleLabelWithText:NSStringFormat(@"定位时间：%@",_positionTimeString?:@"无位置信息") bgColor:[UIColor clearColor] textColor:self.textColor font:17];
        _timeLabel = timeLabel;
        
        [fourthSectionContainer sd_addSubviews:@[statusLabel,locationLabel,timeLabel]];
        
        statusLabel.sd_layout
        .leftSpaceToView(fourthSectionContainer, 15)
        .rightSpaceToView(fourthSectionContainer, 15)
        .topSpaceToView(fourthSectionContainer, 10)
        .heightIs(25);
        
        locationLabel.sd_layout
        .leftEqualToView(statusLabel)
        .topSpaceToView(statusLabel, 5)
        .rightSpaceToView(fourthSectionContainer, 15)
        .autoHeightRatio(0);
        
        timeLabel.sd_layout
        .leftEqualToView(locationLabel)
        .topSpaceToView(locationLabel, 5)
        .rightEqualToView(locationLabel)
        .autoHeightRatio(0);
        
        [fourthSectionContainer setupAutoHeightWithBottomView:timeLabel bottomMargin:10];
    }
    [self.wrapperView addSubview:fourthSectionContainer];
    
    fourthSectionContainer.sd_layout
    .leftEqualToView(self.wrapperView)
    .topSpaceToView(_thirdSectionContainer, 7)
    .rightEqualToView(self.wrapperView);
    
    // 提交按钮
    UIButton *submitButton = [[UIButton alloc] init];
    self.submitButton = submitButton;
    [self.wrapperView addSubview:submitButton];
    
    NSString *title = self.uploadType == UploadImgTypeNormal ? @"提交":@"补拍提交";
    [submitButton setTitle:title forState:UIControlStateNormal];
    [submitButton addTarget:self action:@selector(submitAction:) forControlEvents:UIControlEventTouchUpInside];
    [submitButton setBackgroundColor:[UIColor redColor]];
    
    submitButton.sd_layout
    .leftSpaceToView(self.wrapperView, 15)
    .rightSpaceToView(self.wrapperView, 15)
    .topSpaceToView(_fourthSectionContainer, 20)
    .heightIs(45);
    submitButton.sd_cornerRadius = @(3);
}

- (UIImagePickerController *)imagePicker {
    if (!_imagePicker) {
        _imagePicker = [UIImagePickerController new];
        _imagePicker.delegate = self;
        _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    return _imagePicker;
}

- (void)takePhotoClick:(UIButton *)btn
{
    _presentNextPage = YES;
    
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                [self presentViewController:self.imagePicker animated:YES completion:nil];
            }
        }];
    } else if (status == AVAuthorizationStatusRestricted || status ==  AVAuthorizationStatusDenied) {
        [[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请在系统设置中开启相机权限(设置->隐私->相机)" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去设置", nil] show];
        return;
    } else {
        [self presentViewController:self.imagePicker animated:YES completion:nil];
    }

    _isRetakePhoto = NO;
    self.tempButton = btn;
    
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}

- (void)retakePhotoClick:(UIButton *)btn
{
    _isRetakePhoto = YES;
    self.tempRetakeBtn = btn;
    _presentNextPage = YES;
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}

#pragma mark - CompareLocationTime

- (NSTimeInterval)compareOldDate:(NSString *)oldDate fromNowDate:(NSDate *)nowDate {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *date1 = [formatter dateFromString:oldDate];
    return [nowDate timeIntervalSinceDate:date1];
}

// 判断纯数字
- (BOOL)isPureInt:(NSString*)str {
    NSScanner *scan = [NSScanner scannerWithString:str];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}

#pragma mark - SubmitButtonAction
- (void)submitAction:(UIButton *)btn
{
//#warning 此代码为正式质量压缩图片，正式更新需打开！！！！！
    NSMutableArray *images = [self.imagesArray mutableCopy];
    [images removeObject:@""];
//#warning 此代码为测试质量压缩图片，正式更新需注释掉！！！！！
//    NSArray *images = @[[UIImage imageNamed:@"ceshi_001"],[UIImage imageNamed:@"ceshi_005"],[UIImage imageNamed:@"ceshi_006"]];
    
    
    if (self.uploadType == UploadImgTypeNormal) {// 上传提交
        if (!_installerTextField.text.length) {
            [MBProgressHUD showToast:@"姓名不能为空"];
            return;
        }
        
        NSString *phone = _phoneNumTextField.text;
        if (![self isPureInt:phone] || phone.length != 11 || ![phone hasPrefix:@"1"]) {
            [MBProgressHUD showToast:@"请输入11位有效电话号码"];
            return;
        }
        
        if (images.count != 3) {
            [MBProgressHUD showToast:@"照片不完整"];
            return;
        }
        
        if (_isUnActive) {
            [self show:@"该设备未启用"];
            return;
        }
        
        if (!_installerPosition) {
            [self show:@"手机可能未定位，正在重新定位您的位置"];
            [self getLocation];
            return;
        }
        
        // 验证定位时间和定位范围
        NSTimeInterval difference = [self compareOldDate:_positionTimeString fromNowDate:[NSDate date]];
        CLLocation *eqLocation = [[CLLocation alloc] initWithLatitude:_latitude longitude:_longitude];
        double distance = [_location distanceFromLocation:eqLocation];
//        PPLog(@"time==%lf,distance==%lfM",difference,distance);
//        PPLog(@"start ==> lat == %lf && lng == %lf",_location.coordinate.latitude,_location.coordinate.longitude);
//        PPLog(@"end == >  lat == %lf && lng == %lf",eqLocation.coordinate.latitude,eqLocation.coordinate.longitude);
        if (_isLBSLocation) {
            [self show:@"GPS信号弱，请重新定位"];
            return;
        }

//#warning open!!!!!!!!!!
        if (difference >= 1800.0)
        {// 有效时间30分钟
            [self show:@"定位失效，请重新定位"];
            return;
        }

        if (distance >= 500.0)
        {// 有效距离500米
            [self show:@"请在安装现场拍照"];
            return;
        }
        
        // 先检查照片数量
        [self.requestTool queryEquipImgByEqId:self.eqnoModel.eqId show:YES success:^(NSArray *results) {
            NSArray *result = results[1];
            
            PPLog(@"Query img array == %lu",(unsigned long)((NSArray *)results[1]).count);
         
            if (result.count >= 3) {
                [self showAlert:@"信息已提交,正在审核!"];
                return;
            }
            
            if (result.count >= 1 && result.count < 3) {
                [self showAlert:@"上传失败，照片数量已变更，请重新登录后补拍上传"];
                return;
            }
            
            // 照片来源
            NSString *origin = NSStringFormat(@"--来自%@",[DeviceVersion deviceVersion]);
            
            NSString *installerPosition = NSStringFormat(@"%@(%f,%f)%@",_installerPosition,_location.coordinate.latitude,_location.coordinate.longitude,origin);
            // 设备定位地址
            NSString *eqPosition = NSStringFormat(@"%@(%f,%f)",_eqPosition,_latitude,_longitude);
//            PPLog(@"installerPosition = %@",installerPosition);
//            PPLog(@"eqPosition = %@",eqPosition);
            [self.requestTool uploadImagesByEqId:self.eqnoModel.eqId installer:_installerTextField.text installerPhone:_phoneNumTextField.text installerPosition:installerPosition images:images eqPosition:eqPosition success:^(int status) {
                if (status == 0){
                    _presentNextPage = NO;
                    if ([self.takePhotoType isEqualToString:@"1"]) {// 从工单进入拍照
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"kSendEqNoNotification" object:self.eqnoModel.eqNo userInfo:nil];
                        UIViewController *vc = self.navigationController.viewControllers[2];
                        [self.navigationController popToViewController:vc animated:YES];
                    } else {
                        [self showAlert:@"上传成功"];
                    }
                } else if (status == 1){
                    [self showAlert:@"信息已提交,正在审核!"];
                }
            } failure:^(NSError *error) {
                PPLog(@"照片上传失败 ：%@",error);
            }];
        } failure:^(NSError *error) {
            PPLog(@"查询照片数量失败 ：%@",error);
        }];
        
    } else { //补拍提交
        
        if (_isUnActive) {
            [self show:@"该设备未启用"];
            return;
        }
        // 验证定位时间和定位范围
        NSTimeInterval difference = [self compareOldDate:_positionTimeString fromNowDate:[NSDate date]];
        CLLocation *eqLocation = [[CLLocation alloc] initWithLatitude:_latitude longitude:_longitude];
        double distance = [_location distanceFromLocation:eqLocation];
//        PPLog(@"time==%lf,distance==%lfM",difference,distance);
//        PPLog(@"start ==> lat == %lf && lng == %lf",_location.coordinate.latitude,_location.coordinate.longitude);
//        PPLog(@"end == >  lat == %lf && lng == %lf",eqLocation.coordinate.latitude,eqLocation.coordinate.longitude);
        
        if (_isLBSLocation)
        {
            [self show:@"GPS信号弱，请重新定位"];
            return;
        }
        if (difference >= 1800.0)
        {// 有效时间30分钟
            [self show:@"定位失效，请重新定位"];
            return;
        }
        if (distance >= 500.0)
        {// 有效距离500米
            [self show:@"请在安装现场拍照"];
            return;
        }
        
        if (images.count != 3-self.indexImg.count)
        {
            [self show:@"补拍照片不完整"];
            return;
        }
        
        // 先检查照片数量
//        [MBProgressHUD showLoading:@"正在处理..."];
        [self.requestTool queryEquipImgByEqId:self.eqnoModel.eqId show:YES success:^(NSArray *results) {
            NSArray *result = results[1];

            PPLog(@"query img array == %lu",(unsigned long)((NSArray *)results[1]).count);

            if (result.count >= 3) {
//                [MBProgressHUD hideHUDForView:KEY_WINDOW];
                [self showAlert:@"信息已提交,正在审核!"];
                return;
            }

            if (images.count != 3-result.count) {
//                [MBProgressHUD hideHUDForView:KEY_WINDOW];
                [self showAlert:@"上传失败，照片数量已变更，请重新登录后重新提交上传"];
                return;
            }
            
            [self.requestTool uploadRepearImgByEqId666:self.eqnoModel.eqId images:images types:self.types success:^(int status) {
                if (status == 0) {
                    [self showAlert:@"上传成功"];
                }
            } failure:^(NSError *error) {
                PPLog(@"照片补拍上传失败 = %@",error);
            }];
//            __block NSInteger uploadImageCount = 0;
//            for (int i = 0; i < images.count; i++) {
//                [self.requestTool uploadRepearImgByEqId:self.eqnoModel.eqId img:images[i] type:self.types[i] success:^(int status) {
//                    PPLog(@"成功回调：%d",status);
//                    if (status == 0){
//                        uploadImageCount ++;
//                        if (uploadImageCount == images.count) {
//                            [MBProgressHUD hideHUDForView:KEY_WINDOW];
//                            [self showAlert:@"上传成功"];
//                        }
//                    } else if (status == 1){
//                        [self showAlert:@"上传失败，照片数量已变更，请重新登录后重新提交上传"];
//                    }
//                } failure:^(NSError *error) {
//                    PPLog(@"照片上传失败 ：%@",error);
//                }];
//            }
        } failure:^(NSError *error) {
            PPLog(@"查询照片数量失败 ：%@",error);
        }];
    }
}

- (void)showAlert:(NSString *)message
{
    UIAlertController *controller = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    [controller addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        _presentNextPage = NO;
        [self.navigationController popViewControllerAnimated:YES];
    }]];
    [self presentViewController:controller animated:YES completion:nil];
}

- (void)show:(NSString *)message {
    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
}

#pragma mark - ImagePicker Delegate -
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    CGFloat w = image.size.width;
    CGFloat h = image.size.height;
    
    CGFloat ratio = 0.0;
    
    ratio = h > w ? (h / w * 0.7) : (h / w * 0.9);
    
    /* NO为拍照 YES为重新拍照 */
    if (_isRetakePhoto) {
        [self retakePhoto:self.tempRetakeBtn.tag image:image ratio:ratio];
    } else {
        [self displayPhoto:self.tempButton.tag image:image ratio:ratio];
    }
}

- (void)displayPhoto:(NSInteger)tag image:(UIImage *)image ratio:(CGFloat)ratio
{
    self.tempButton.sd_layout.autoHeightRatio(ratio);
    
    [self.tempButton updateLayout];
    
    if (tag == 10)
    {
        _firstImgView.hidden = NO;
        _firstImgView.image = image;
        [self.imagesArray replaceObjectAtIndex:0 withObject:_firstImgView.image];
    }
    else if (tag == 11)
    {
        _secondImgView.hidden = NO;
        _secondImgView.image = image;
        [self.imagesArray replaceObjectAtIndex:1 withObject:_secondImgView.image];
    }
    else if (tag == 12)
    {
        _thirdImgView.hidden = NO;
        _thirdImgView.image = image;
        [self.imagesArray replaceObjectAtIndex:2 withObject:_thirdImgView.image];
    }
    else if (tag == 13)
    {
//        _fourthImgView.hidden = NO;
//        _fourthImgView.image = image;
//        [self.imagesArray replaceObjectAtIndex:3 withObject:_fourthImgView.image];
    }
//    PPLog(@"===%ld",self.imagesArr.count);
}

- (void)retakePhoto:(NSInteger)tag image:(UIImage *)image ratio:(CGFloat)ratio
{
    if (tag == 30)
    {
        if (!_firstImgView.hidden) {
            _firstButton.sd_layout.autoHeightRatio(ratio);
            [_firstButton updateLayout];
            _firstImgView.image = image;
            [self.imagesArray replaceObjectAtIndex:0 withObject:_firstImgView.image];
        }
    }
    else if (tag == 31)
    {
        if (!_secondImgView.hidden) {
            _secondButton.sd_layout.autoHeightRatio(ratio);
            [_secondButton updateLayout];
            _secondImgView.image = image;
            [self.imagesArray replaceObjectAtIndex:1 withObject:_secondImgView.image];
        }
    }
    else if (tag == 32)
    {
        if (!_thirdImgView.hidden) {
            _thirdButton.sd_layout.autoHeightRatio(ratio);
            [_thirdButton updateLayout];
            _thirdImgView.image = image;
            [self.imagesArray replaceObjectAtIndex:2 withObject:_thirdImgView.image];
        }
    } else if (tag == 33)
    {
//        if (!_fourthImgView.hidden) {
//            _fourthButton.sd_layout.autoHeightRatio(ratio);
//            [_fourthButton updateLayout];
//            _fourthImgView.image = image;
//            [self.imagesArray replaceObjectAtIndex:3 withObject:_fourthImgView.image];
//        }
    }
//    PPLog(@"%ld",self.imagesArr.count);
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 点击图片 -
- (void)tapImageView:(UITapGestureRecognizer *)tap
{
    UIImageView *imgView = (UIImageView *)tap.view;
    UIImage *image = imgView.image;
    
    //copy数组
    NSMutableArray *images = [self.imagesArray mutableCopy];
    //删除空的
    [images removeObject:@""];
    PPLog(@"images count = %ld", images.count);
    
    //判断位置
    int index = -1;
    for (int i = 0; i < images.count; i++) {
        if (image == images[i]) {
            index = i;
        }
    }
    [XLPhotoBrowser showPhotoBrowserWithImages:images currentImageIndex:index];
}

- (UIButton *)buttonWithTitle:(NSString *)title bgColor:(UIColor *)bgColor sel:(SEL)sel
{
    UIButton *button = [UIButton new];
    [button setTitle:title forState:UIControlStateNormal];
    button.backgroundColor = bgColor;
    [button addTarget:self action:sel forControlEvents:UIControlEventTouchUpInside];
    return button;
}

- (UILabel *)titleLabelWithText:(NSString *)text bgColor:(UIColor *)bgColor textColor:(UIColor *)textColor font:(CGFloat)font {
    UILabel *titleLabel = [UILabel new];
    
    titleLabel.text = text;
    titleLabel.font = SYSTEM_FONT(font);
    titleLabel.textAlignment = NSTextAlignmentLeft;
    titleLabel.textColor = textColor;
    titleLabel.backgroundColor = bgColor;
    return titleLabel;
}

- (NSMutableArray *)imagesArray {
    if (!_imagesArray) {
        _imagesArray = [NSMutableArray arrayWithObjects:@"",@"",@"", nil];
    }
    return _imagesArray;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
